package apigateway.project.core.helper;

import apigateway.project.core.context.GlobalContext;
import apigateway.project.core.response.GlobalResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import org.asynchttpclient.Response;

public class ResponseHelper {
    /**
     *  写回
     * @param ctx
     */
    public static void writeResponse(GlobalContext ctx){
        if(ctx.getStatus() == GlobalContext.status_type.WRITTEN){
            FullHttpResponse httpResponse = getHttpResponse(ctx, ctx.getReponse());
            if(!ctx.isKeepAlive()){
                ctx.getCtx().writeAndFlush(httpResponse);
            }else{
                httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                ctx.getCtx().writeAndFlush(httpResponse);
            }
            ctx.completed();
        }
    }

    public static FullHttpResponse getHttpResponse(GlobalContext ctx, GlobalResponse response){
        Response futureResponse = response.getResponse();
        ByteBuf byteBuf;
        if(futureResponse != null){
            byteBuf = Unpooled.wrappedBuffer(futureResponse.getResponseBodyAsByteBuffer());
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,response.getStatus(),byteBuf);
            httpResponse.headers().add(response.getHeaders());
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
            return httpResponse;
        } else if (response.getContent()!=null) {
            byteBuf = Unpooled.wrappedBuffer(response.getContent().getBytes());
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,response.getStatus(),byteBuf);
            httpResponse.headers().add(response.getHeaders());
            return httpResponse;
        }else {
            byteBuf = Unpooled.wrappedBuffer("".getBytes());
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,response.getStatus(),byteBuf);
            httpResponse.headers().add(response.getHeaders());
            return httpResponse;
        }
    }
}
